<?php

namespace app\admin\controller\code\task;

use app\admin\service\GroupReportExportService;
use app\admin\service\ReportService;
use app\admin\service\TaskService;
use app\admin\service\UserService;
use app\BaseController;
use app\model\ConfigModel;
use app\model\DepartmentModel;
use app\model\not_del\UserModel as NotDelUserModel;
use app\model\RatingScaleModel;
use app\model\TaskContinuousEvaluationModel;
use app\model\TaskModel;
use app\model\TaskRatingScaleModel;
use app\model\TaskUserModel;
use app\model\UnitModel;
use app\model\UserModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 生成过期码
     * @return bool|string
     */
    public function taskCode(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $ConfigModel = new ConfigModel();
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'evaluation_task'
            ])->value('value') ?? '';
            $config = json_decode($data, true);
            $lock = md5($param['id'].'task_code'.time() . uniqid());
            if (!empty($config['code_valid']) && $config['code_valid'] > 0){
                cache($lock,$param['id'],intval($config['code_valid']));
            }else{
                cache($lock,$param['id']);
            }
            $url = '/#/scanCodeLogin?id='.$lock;
            return success($url);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 发布
     * @return bool|string
     */
    public function release(): bool|string
    {
        $TaskModel = new TaskModel();
        $TaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'name|任务名称' => 'require',
                'department_id|部门' => 'require',
                'type|量表类型' => 'require',
                'is_time|是否限时' => 'require',
                'rating_scale|量表' => 'require',
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['rating_scale_count'] = count($param['rating_scale']);
            $param['time'] = time();
            $param['code_type'] = 2;
            if ($param['is_time'] == 1) {
                if (empty($param['end_time'])) throw new \Exception('请填写开始和结束时间！');
                if ($param['start_time'] <= $param['time'] && $param['end_time'] > $param['time']) {
                    //在任务时间内将任务设为进行中
                    $param['status'] = 2;
                }
            } else {
                $param['status'] = 2;
            }
            if (!empty($param['result_read_auth'])) {
                $param['result_read_auth'] = implode(',', $param['result_read_auth']);
            }
            $ConfigModel = new ConfigModel();
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'evaluation_task'
            ])->value('value') ?? '';
            $config = json_decode($data, true);
            if (isset($config['is_continuous'])){
                $param['is_continuous'] = $config['is_continuous'] ? 1 : 0;
            }
            $param['is_redo'] = $config['is_redo'] ?? 0;
            $param['is_temporary'] = $config['is_temporary'] ?? 0;
            $UserModel = new UserModel();
            $uid = $UserModel->where('department_id','=',$param['department_id'])->column('id');
            // unset($param['department_id']);
            $param['user_count'] = count($uid);
            foreach ($param['rating_scale'] as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    if ($item['rating_scale_id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                    $continuousData[] = [
//                        'task_id' => $task_id,
                        'rating_scale_id' => $item['rating_scale_id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $param['time']
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
//                    'task_id' => $task_id,
                    'rating_scale_id' => $item['rating_scale_id'],
                    'pack_id' => $item['pack_id'],
                    'time' => $param['time']
                ];
                if (!empty($uid)){
                    foreach ($uid as $v) {
                        $task_user[] = [
//                            'task_id' => $task_id,
                            'rating_scale_id' => $item['rating_scale_id'],
                            'uid' => $v,
                            'time' => $param['time']
                        ];
                    }
                }
            }
            unset($param['rating_scale']);
            $task_id = $TaskModel->insertGetId($param);
            if (!empty($task_rating_scale)) {
                foreach ($task_rating_scale as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskRatingScaleModel = new TaskRatingScaleModel();
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            if (!empty($continuousData)){
                foreach ($continuousData as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskContinuousEvaluationModel = new TaskContinuousEvaluationModel();
                $TaskContinuousEvaluationModel->insertAll($continuousData);
            }
            if (!empty($task_user)){
                foreach ($task_user as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskUserModel = new TaskUserModel();
                $TaskUserModel->insertAll($task_user);
            }
            $TaskModel->commit();
            return success([
                'task_id' => $task_id
            ]);
        } catch (\Exception $e) {
            $TaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 发布
     * @return bool|string
     */
    public function update(): bool|string
    {
        $TaskModel = new TaskModel();
        $TaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'name|任务名称' => 'require',
                'department_id|部门' => 'require',
                'type|量表类型' => 'require',
                'is_time|是否限时' => 'require',
                'rating_scale|量表' => 'require',
            ]);
            $info = $TaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info->status != 1) throw new \Exception('未开始的任务才能编辑全部信息！');
            $info->save([
                'is_del' => 1,
                'del_time' => time(),
            ]);
            unset($param['id']);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['rating_scale_count'] = count($param['rating_scale']);
            $param['time'] = time();
            if ($param['is_time'] == 1) {
                if (empty($param['end_time'])) throw new \Exception('请填写开始和结束时间！');
                if ($param['start_time']??0 <= $param['time'] && $param['end_time'] > $param['time']) {
                    //在任务时间内将任务设为进行中
                    $param['status'] = 2;
                }
            } else {
                $param['status'] = 2;
            }
            if (!empty($param['result_read_auth'])) {
                $param['result_read_auth'] = implode(',', $param['result_read_auth']);
            }
            $ConfigModel = new ConfigModel();
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'evaluation_task'
            ])->value('value') ?? '';
            $config = json_decode($data, true);
            if (isset($config['is_continuous'])){
                $param['is_continuous'] = $config['is_continuous'] ? 1 : 0;
            }
            $param['is_redo'] = $config['is_redo'] ?? 0;
            $param['is_temporary'] = $config['is_temporary'] ?? 0;
            $UserModel = new UserModel();
            // unset($param['department_id']);
            $param['user_count'] = $UserModel->where('department_id','=',$param['department_id'])->count('id');
            foreach ($param['rating_scale'] as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    if ($item['rating_scale_id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                    $continuousData[] = [
//                        'task_id' => $task_id,
                        'rating_scale_id' => $item['rating_scale_id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $param['time']
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
//                    'task_id' => $task_id,
                    'rating_scale_id' => $item['rating_scale_id'],
                    'pack_id' => $item['pack_id'],
                    'time' => $param['time']
                ];

                if (!empty($uid)){
                    foreach ($uid as $v) {
                        $task_user[] = [
//                            'task_id' => $task_id,
                            'rating_scale_id' => $item['rating_scale_id'],
                            'uid' => $v,
                            'time' => $param['time']
                        ];
                    }
                }
            }
            unset($param['rating_scale']);
            $param['code_type'] = 2;
            $task_id = $TaskModel->insertGetId($param);
            if (!empty($task_rating_scale)) {
                foreach ($task_rating_scale as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskRatingScaleModel = new TaskRatingScaleModel();
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            if (!empty($continuousData)){
                foreach ($continuousData as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskContinuousEvaluationModel = new TaskContinuousEvaluationModel();
                $TaskContinuousEvaluationModel->insertAll($continuousData);
            }
            if (!empty($task_user)){
                foreach ($task_user as &$v) {
                    $v['task_id'] = $task_id;
                }
                $TaskUserModel = new TaskUserModel();
                $TaskUserModel->insertAll($task_user);
            }
            $TaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $TaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑
     * @return bool|string
     */
    public function update2(): bool|string
    {
        $TaskModel = new TaskModel();
        $TaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
//                'name|任务名称' => 'require',
                'is_time|是否限时' => 'require',
            ]);
            if ($param['is_time'] == 1) {
                if (empty($param['end_time'])) throw new \Exception('请填写开始和结束时间！');
                $time = time();
                if ($param['start_time']??0 <= $time && $param['end_time'] > $time) {
                    //在任务时间内将任务设为进行中
                    $param['status'] = 2;
                }
            } else {
                $param['status'] = 2;
            }
            $info = $TaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['result_read_auth'])) {
                $param['result_read_auth'] = implode(',', $param['result_read_auth']);
            }
            $info->save($param);
            $TaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $TaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 发布列表
     * @return bool|string
     */
    public function releaseList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['user_complete_rate'])) {
                $TaskService = new TaskService($this->app);
                $CompletionStatus = $TaskService->CompletionStatus($param['user_complete_rate']);
                $where[] = ['user_complete_rate', 'between', $CompletionStatus['value']];
            }
            if (!empty($param['id'])) {
                $where[] = ['id', 'in', $param['id']];
            }
            if (!empty($param['role_mode'])) {
                $UserModel = new UserModel();
                $uid = $UserModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['role_mode','=',$param['role_mode']]
                ])->column('id');
                if (!empty($uid)) {
                    $where[] = ['uid','in',$uid];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            $where[] = ['code_type', '=', 2];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $TaskModel = new TaskModel();
            $query = $TaskModel->where($where);
            $data = $query->with([
                'userNameRoleName' => function ($query) {
                    $query->with(['roleName']);
                }
            ])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                if (empty($item['role_name'])) $item['role_name'] = '超级管理员';
                $item['user_complete_rate'] = $item['user_complete_rate'] . '%';
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $TaskModel = new TaskModel();
            $info = $TaskModel->with([
                'taskRatingScale' => function ($query) {
                    $query->with([
                        'ratingScale',
                        'RatingScalePack'
                    ]);
                },
                'taskContinuousEvaluation' => function ($query) {
                    $query->with([
                        'RatingScaleFactor',
                        'continuityRatingScale'
                    ]);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $ContinuousData = [];
            foreach ($info['taskContinuousEvaluation'] as $v) {
                $ContinuousData[$v['rating_scale_id']]['factor'][] = [
                    'factor_id' => $v['factor_id'],
                    'factor_name' => $v['factor_name'],
                    'rating_scale_id' => $v['continuity_rating_scale_id'],
                    'rating_scale_name' => $v['continuity_rating_scale_name'],
                ];
            }
            foreach ($info['taskRatingScale'] as $v) {
                $info['rating_scale'][] = [
                    'rating_scale_id' => $v['rating_scale_id'],
                    'rating_scale_name' => $v['rating_scale_name'],
                    'pack_id' => $v['pack_id'],
                    'pack' => $v['rating_scale_pack_name'],
                    'factor' => $ContinuousData[$v['rating_scale_id']]['factor']??[]
                ];
            }
            $info['result_read_auth'] = explode(',', $info['result_read_auth']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 报告列表
     * @return bool|string
     */
    public function reportList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require'
            ]);
            $where = [];
            $TaskUserResultModel = new CodeTaskUserResultModel();
            $task_id = $TaskUserResultModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['admin_del','=',0]
            ])->distinct(true)->column('task_id');
            if (!empty($task_id)){
                $where[] = ['id', 'in', $task_id];
            }else{
                $where[] = ['id', '=', -1];
            }
            $CodeTaskModel = new CodeTaskModel();
            $data = $CodeTaskModel->where($where)->with([
                'user' => function ($query) {
                    $query->with(['unitName']);
                }
            ])->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 报告详情
     * @return bool|string
     */
    public function reportInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $CodeTaskModel = new CodeTaskModel();
            $info = $CodeTaskModel->with([
                'CodeTaskRatingScale' => function ($query) {
                    $query->with(['RatingScale']);
                }
            ])->find($param['id']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评用户部门
     * @return bool|string
     */
    public function reportUserDepartment(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require'
            ]);
            $CodeTaskUserResultModel = new CodeTaskUserResultModel();
            $UserModel = new UserModel();
            $where = [];
            $where[] = ['task_id', '=', $param['task_id']];
            $where[] = ['rating_scale_id', '=', $param['rating_scale_id']];
            //查询满足条件报告
            if (isset($param['answer_role']) && strlen($param['answer_role']) > 0) {
                $where[] = ['answer_role', '=', $param['answer_role']];
            }
            if (isset($param['is_warning']) && strlen($param['is_warning']) > 0) {
                $where[] = ['is_warning', '=', $param['is_warning']];
            }
            if (isset($param['is_explain']) && strlen($param['is_explain']) > 0) {
                $where[] = ['is_explain', '=', $param['is_explain']];
            }
            if (!empty($param['warning_factor_id'])) {
                $where[] = ['warning_factor_id', '=', $param['warning_factor_id']];
            }
            if (!empty($param['name']) && !empty($param['sex'])) {
                $uids = $UserModel->where([
                    ['name', 'like', '%' . $param['name'] . '%'],
                    ['sex', '=', $param['sex']]
                ])->column('id');
                if (count($uids) > 0) {
                    $where[] = ['uid', 'in', $uids];
                } else {
                    $where[] = ['id', '=', -1];
                }
            } else {
                if (!empty($param['name'])) {
                    $uids = $UserModel->where('name', 'like', '%' . $param['name'] . '%')->column('id');
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
                if (!empty($param['sex'])) {
                    $uids = $UserModel->where('sex', '=', $param['sex'])->column('id');
                    if (count($uids) > 0) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
            }
            $user = $CodeTaskUserResultModel->field('id,uid')->where($where)
                ->with([
                    'user'
                ])->select()->toArray();
            $departmentIds = array_column($user, 'department_id');
            $departmentData = [];
            foreach ($user as $item) {
                $departmentData[$item['department_id']]['user_list'][] = $item;
            }
            $UserService = new UserService($this->app);
            if (!empty($param['unit_id'])){
                $departmentAllIds = $UserService->getDepartmentAllIds($param['unit_id'], $departmentIds);
            }else{
                $departmentAllIds = $UserService->getDepartmentAllIds($this->userData['unit_id'], $departmentIds);
            }
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->field('id,pid,name')
                ->where('id', 'in', $departmentAllIds)->select()->toArray();
            foreach ($data as &$item) {
                $item['user_list'] = $departmentData[$item['id']]['user_list'] ?? [];
            }
            $data2 = buildTree($data);
            if (empty($data2)) {
                $data3 = [];
            }else{
                if (!empty($param['unit_id'])){
                    $UnitModel = new UnitModel();
                    $data3[] = [
                        'id' => 0,
                        'name' => $UnitModel->where('id','=',$param['unit_id'])->value('name') ?? '',
                        'child' => $data2,
                        'users' => []
                    ];
                }else{
                    $data3[] = [
                        'id' => 0,
                        'name' => $this->userData['unit']['name'] ?? '',
                        'child' => $data2,
                        'users' => []
                    ];
                }
            }
            return success($data3);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 二维码-任务测评团体报告
     * @return bool|string
     */
    public function codeTaskGroupReport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'department_id|部门ID' => 'require'
            ]);
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->field('id,pid')->where('unit_id', '=', $this->userData['unit_id'])->select()->toArray();
            $DepartmentIds = getAllSubcategories($data, $param['department_id']);
            $DepartmentIds = array_column($DepartmentIds, 'id');
            $DepartmentIds[] = (int)$param['department_id'];
            $UserModel = new UserModel();
            $uids = $UserModel->where('department_id', 'in', $DepartmentIds)->column('id');
            $GroupReportExportService = new GroupReportExportService($this->app);
            return $GroupReportExportService->TaskGroupReportExportData($param['task_id'], $param['rating_scale_id'], $uids);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }

    }

    /**
     * 个人报告
     * @return bool|string
     */
    public function personReport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getCodeSelfEvaluationReportInfo($param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 查询任务状态
     * @return bool|string
     */
    public function taskStatus(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskModel = new TaskModel();
            if (is_array($id)) {
                $status = $TaskModel->where('id', 'in', $id)->column('status');
            } else {
                $status = $TaskModel->where('id', '=', $id)->column('status');
            }
            $status = array_unique($status);
            return success($status);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除任务
     * @return false|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskModel = new TaskModel();
            if (is_array($id)) {
                $TaskModel->where('id', 'in', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            } else {
                $TaskModel->where('id', '=', $id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 终止任务
     * @return false|string
     */
    public function terminateTask(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskModel = new TaskModel();
            $info = $TaskModel->find($id);
            if ($info->status == 3) throw new \Exception('任务已终止！');
            $info->status = 3;
            $info->save();
            return success('任务已终止！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取任务量表
     * @return false|string
     */
    public function getTaskRatingScale(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $data = $TaskRatingScaleModel->field('id,rating_scale_id')
                ->with(['ratingScale'])
                ->where('task_id', '=', $id)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 发布人身份选择器
     * @return bool|string
     */
    public function PublisherSelector(): bool|string
    {
        try {
            $mode = [
                0 => '超级管理员',
                1 => '普通管理员',
                2 => '咨询师',
                3 => '用户'
            ];
            $TaskModel = new TaskModel();
            $uids = $TaskModel->where('unit_id', '=', $this->userData['unit_id'])->column('uid');
            $UserModel = new NotDelUserModel();
            $role_mode = $UserModel->where('id', 'in', $uids)->column('role_mode');
            $role_mode = array_unique($role_mode);
            $data = [];
            foreach ($role_mode as $item) {
                $data[] = [
                    'id' => $item,
                    'name' => $mode[$item]
                ];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取任务用户
     * @return false|string
     */
    public function getTaskUser(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $data = $this->getTaskUser2($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function getTaskUser2($id): array
    {
        $TaskUserModel = new TaskUserModel();
        $data = $TaskUserModel->field('uid,is_finish')->where('task_id', '=', $id)->with([
            'taskUser'
        ])->order('is_finish', 'asc')->group('uid')->select()->toArray();
        $departmentIds = array_unique(array_column($data, 'department_id'));
        $UserService = new UserService($this->app);
        $NotDelDepartmentAll = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
        $DepartmentAdminAll = $UserService->getDepartmentAdminAll($departmentIds);
        foreach ($data as &$item) {
            $item['ascription_name'] = $NotDelDepartmentAll[$item['department_id']]['ascription_name'] ?? '';
            $item['department_name'] = $NotDelDepartmentAll[$item['department_id']]['all_name'] ?? '';
            $item['department_admin'] = $DepartmentAdminAll[$item['department_id']]['user_name'] ?? '';
        }
        return $data;
    }

    /**
     * 已发布任务记录-高级筛选
     * @return bool|string
     */
    public function filter(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $UserModel = new UserModel();
            $RatingScaleModel = new RatingScaleModel();
            $CodeTaskUserResultModel = new CodeTaskUserResultModel();
            if (!empty($param['department_id'])) {
                $uid = $UserModel->where('department_id', 'in', $param['department_id'])->column('id');
                if (count($uid)) {
                    $where[] = ['uid', 'in', $uid];
                }else{
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['type_id'])) {
                $rating_scale_id = $RatingScaleModel->where('type_id', 'in', $param['type_id'])->column('id');
                if (count($rating_scale_id)) {
                    $where[] = ['rating_scale_id', 'in', $rating_scale_id];
                } else {
                    $where[] = ['id', '=', -1];
                }
            }
            if (!empty($param['result_read_auth'])){
                foreach ($param['result_read_auth'] as $item) {
                    $where[] = ['result_read_auth', 'like', '%'.$item.'%','or'];
                }
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $task_id = $CodeTaskUserResultModel->where($where)->distinct(true)->column('task_id');
            $TaskWhere = [];
            if (count($task_id)){
                $TaskWhere[] = ['id', 'in', $task_id];
            }else{
                $TaskWhere[] = ['id', '=', -1];
            }
            if (!empty($param['uid'])){
                $TaskWhere[] = ['uid', 'in', $param['uid']];
            }
            if (!empty($param['status'])){
                $TaskWhere[] = ['status', '=', $param['status']];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $TaskWhere[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $TaskWhere[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $TaskWhere[] = ['time', '<=', $param['end_time']];
                }
            }
            $CodeTaskModel = new CodeTaskModel();
            $ids = $CodeTaskModel->where($TaskWhere)->column('id');
            if (empty($ids)) {
                $ids = [-1];
            }
            return success($ids);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 发布人选择器
     * @return bool|string
     */
    public function PublisherSelector2(): bool|string
    {
        try {
            $CodeTaskModel = new CodeTaskModel();
            $uid = $CodeTaskModel->where('unit_id', '=', $this->userData['unit_id'])->column('uid');
            $uid = array_unique($uid);
            $UserModel = new NotDelUserModel();
            $data = $UserModel->field('id,name')
                ->where('id', 'in', $uid)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除任务测评报告
     * @return bool|string
     */
    public function taskEvaluationReportDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $CodeTaskUserResultModel = new CodeTaskUserResultModel();
            $CodeTaskModel = new CodeTaskModel();
            if (is_array($id)) {
                $uids = $CodeTaskModel->where('id', 'in', $id)->column('uid');
                $uids = array_unique($uids);
                if (!in_array($this->userData['id'], $uids) || count($uids) > 1) throw new \Exception('任务发布人才能删除！');
                $CodeTaskUserResultModel->where('task_id', 'in', $id)->update([
                    'admin_del' => 1,
                ]);
            } else {
                $uid = $CodeTaskModel->where('id', '=', $id)->value('uid');
                if ($uid != $this->userData['id']) throw new \Exception('任务发布人才能删除！');
                $CodeTaskUserResultModel->where('task_id', '=', $id)->update([
                    'admin_del' => 1,
                ]);
            }
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除任务对应量表的报告
     * @return bool|string
     */
    public function taskRatingScaleReportDel(): bool|string
    {
        try {
            $task_id = $this->request->param('task_id');
            $rating_scale_id = $this->request->param('rating_scale_id');
            $TaskUserResultModel = new CodeTaskUserResultModel();
            $TaskUserResultModel->where([
                'task_id' => $task_id,
                'rating_scale_id' => $rating_scale_id
            ])->update([
                'admin_del' => 1,
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }




}